/**
 * @author: zhazhjie
 * @email: zhazhjie@vip.qq.com
 * @date: 2018-11-05 16:25:40
 * @version: 1.0
 */
import Vue from 'vue';
import router from '../router'
import store from '../store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken} from "../utils/util";

NProgress.configure({showSpinner: false});

const whiteList = ['/login', '/404', '/customModule', '/preview'];

function setCacheMenu(to) {
  let {fullPath, path, meta} = to;
  let {name} = meta || {};
  if (name && !whiteList.includes(path)) {
    store.commit("pushCacheMenu", {path: fullPath, name});
  }
}

router.beforeEach((to, from, next) => {
  setCacheMenu(to);
  NProgress.start();
  if (whiteList.indexOf(to.path) > -1) {
    next();
  } else if (getToken()) {
    if (!store.state.initFlag) {
      store.dispatch('getUserInfo');
      store.dispatch('listUserMenu').then(() => {
        Vue.nextTick(() => {
          next({...to, replace: true});
        });
      });
    } else {
      next();
    }
  } else {
    next({path: '/login?redirectUrl=' + to.fullPath, replace: true});
  }
});

router.afterEach(() => {
  NProgress.done();
});
